package jgl.vajra.management.part.vehicle.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.annotation.NonNull;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.PeripheralPoiBean;
import jgl.vajra.management.bean.WorkplaceBean;
import jgl.vajra.management.databinding.ActivityWorkingFieldBinding;
import jgl.vajra.management.event.WorkingFieldEvent;
import jgl.vajra.management.event.WorkplaceEvent;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.part.vehicle.contract.WorkingFieldContract;
import jgl.vajra.management.part.vehicle.viewModel.WorkingFieldViewModel;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.permissions.PermissionListener;
import jgl.vajra.management.widget.permissions.PermissionsUtil;
import jgl.vajra.management.widget.utils.ToastUtils;

/**
 * 干活地
 */
@CreateViewModel(WorkingFieldViewModel.class)
public class WorkingFieldActivity extends BaseMVVMActivity<WorkingFieldViewModel, ActivityWorkingFieldBinding> implements WorkingFieldContract.View {
    private BaiduMap mBaiduMap;
    private MapStatus mapBuild;
    private PeripheralPoiBean data;

    @Override
    public int getLayoutId() {
        return R.layout.activity_working_field;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        mBinding.toolbar.setNavigationIcon(R.drawable.ic_left_arrow_white_bg);
        mBinding.toolbar.setNavigationOnClickListener(view -> finish());
        //禁止百度地图的手势
      /*  UiSettings settings = mBinding.mapView.getMap().getUiSettings();
        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setZoomGesturesEnabled(false);//获取是否允许缩放手势返回:是否允许缩放手势
        */
        mBinding.mapView.showScaleControl(false);  // 设置比例尺是否可见（true 可见/false不可见）
        mBinding.mapView.showZoomControls(false);  // 设置缩放控件是否可见（true 可见/false不可见）
        View child = mBinding.mapView.getChildAt(1); // 找到百度LOGO控件对象
        if ((child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);  // 设置child这个控件是否可见（VISIBLE 可见/INVISIBLE不可见 /GONE 完全隐藏）
        }

        mBaiduMap = mBinding.mapView.getMap();
        //开启热力图
        mBaiduMap.setBaiduHeatMapEnabled(false);


        LatLng ll = new LatLng(28.276159, 113.087089);
        mapBuild = new MapStatus.Builder()
                .target(ll)
                .zoom(18f)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);

        addMaker(28.276159, 113.087089, true);
        addMaker(28.276275, 113.087632, false);
        addMaker(28.276275, 113.088244, true);
        addMaker(28.276275, 113.087356, false);

        mBaiduMap.setOnMarkerClickListener(marker -> {

            View view = View.inflate(WorkingFieldActivity.this, R.layout.view_working_field, null);
            //构造InfoWindow
            //-100 InfoWindow相对于point在y轴的偏移量
            InfoWindow mInfoWindow = new InfoWindow(view, marker.getPosition(), -150);
            //使InfoWindow生效
            mBaiduMap.showInfoWindow(mInfoWindow);
            ImageView ivClose = view.findViewById(R.id.iv_close);
            ivClose.setOnClickListener(v -> {
                //关闭InfoWindow
                mBaiduMap.hideInfoWindow();
            });

            TextView llItem = view.findViewById(R.id.ll_item);
            llItem.setOnClickListener(v->{
                IntentManager.toOwnerDetailsActivity(this);
            });

            return false;
        });


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            //地图状态开始改变。
            public void onMapStatusChangeStart(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            //地图状态改变结束
            public void onMapStatusChangeFinish(MapStatus status) {
                //改变结束之后，获取地图可视范围的中心点坐标
                LatLng latLng = status.target;
                //拿到经纬度之后，就可以反地理编码获取地址信息了
                GeoCoder geocoder = GeoCoder.newInstance();
                geocoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        String name = "";
                        if (reverseGeoCodeResult.getPoiRegionsInfoList() != null && reverseGeoCodeResult.getPoiRegionsInfoList().size() != 0)
                            name = reverseGeoCodeResult.getPoiRegionsInfoList().get(0).getRegionName();
                        else if (reverseGeoCodeResult.getPoiList() != null && reverseGeoCodeResult.getPoiList().size() != 0)
                            name = reverseGeoCodeResult.getPoiList().get(0).name;

                        if (TextUtils.isEmpty(name)) {
                            ToastUtils.showShort("定位失败，请重试或手动输入地址");
                            return;
                        }
                        String address = String.format("%s%s", reverseGeoCodeResult.getAddressDetail().city, reverseGeoCodeResult.getAddressDetail().district);
                        data=new PeripheralPoiBean(name,address,latLng.latitude,latLng.longitude,reverseGeoCodeResult.getAddressDetail().city);
                        mBinding.tvName.setText(name);
                        mBinding.tvAddress.setText(address);
                    }
                });

//这个要放在后面！！！！！！！
                LatLng point = new LatLng(latLng.latitude, latLng.longitude);
                geocoder.reverseGeoCode(new ReverseGeoCodeOption().location(point));

            }

            //地图状态变化中
            public void onMapStatusChange(MapStatus status) {
            }
        });
    }

    public void addMaker(double longitude, double latitude, boolean state) {
        //定义Maker坐标点
        LatLng point = new LatLng(longitude, latitude);
        //构建Marker图标
        BitmapDescriptor bitmap;
        if (state) {
            bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_vehicle_free);
        } else {
            bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_vehicle_work);
        }

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions options = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(options);

    }

    @Override
    public void onResume() {
        mBinding.mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mBinding.mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mBinding.mapView.onDestroy();
        super.onDestroy();
    }

    //回到当前位置
    @Override
    public void onReposition() {
        if (mapBuild != null) {
            MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
            mBaiduMap.animateMapStatus(mapStatusUpdate);
        }
    }

    //通讯录
    @Override
    public void onMailList() {
        String[] permissions = {
                Manifest.permission.READ_CONTACTS,

        };
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );
    }

    // 确定吊货地
    @Override
    public void onDetermine() {
        String name = mBinding.etName.getText().toString().trim();
        String phone = mBinding.etPhone.getText().toString().trim();

        if(TextUtils.isEmpty(name)||TextUtils.isEmpty(phone)){
            ToastUtils.showShort("请完善联系人");
            return;
        }
        WorkplaceBean bean =new WorkplaceBean();
        bean.name=name;
        bean.phone=phone;
        bean.address=data.address;
        bean.detailedAddress=data.detailedAddress;
        bean.latitude=data.latitude;
        bean.longitude=data.longitude;
        EventBus.getDefault().post(new WorkplaceEvent(bean));
        finish();
    }

    //修改地址
    @Override
    public void onModifyAddress() {
        IntentManager.toPeripheralPoiActivity(this);
    }

    //常用地址
    @Override
    public void onCommonAddress() {
       IntentManager.toCommonAddressActivity(this);
    }

    /* * 跳转联系人列表的回调函数 * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = getPhoneContacts(uri);
            mBinding.etName.setText(contacts != null ? contacts[0] : "");
            mBinding.etPhone.setText(contacts != null ? contacts[1] : "");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone.close();
            }
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }


    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWorkingFieldEvent(WorkingFieldEvent event) {
        data = event.data;

        mBinding.tvName.setText(event.data.detailedAddress);
        mBinding.tvAddress.setText(event.data.address);
    }
}
